/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package csci6450.chickenFriedFS.metaServer.threads;

import csci6450.chickenFriedFS.metaServer.NuggetServerInfoLog;
import csci6450.chickenFriedFS.metaServer.RuntimeSettings;
import csci6450.chickenFriedFS.nuggetCore.NuggetServerInfo;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author jacobschoen
 */
public class ReplicationManager extends Thread {

    private ServerSocket serverSocket;

    // <editor-fold defaultstate="collapsed" desc=" UML Marker ">
    // #[regen=yes,id=DCE.3D8ECDEE-C845-9D58-12E2-7621FC57B17D]
    // </editor-fold>
    public ReplicationManager() throws IOException {
        this.serverSocket = new ServerSocket(RuntimeSettings.getInstance().getReplicationPort());
        System.out.println("Replication Manager listening for NuggetServer on port " + RuntimeSettings.getInstance().getReplicationPort() + ".");
    }

    @Override
    public void run() {
        while (true) {
            Socket client = null;
            try {
                client = this.serverSocket.accept();
                Connect c = new Connect(client);
                c.start();
            } catch (Exception e) {
                e.printStackTrace();
            } 
        }
    }

    class Connect extends Thread {

        private Socket client = null;
        private ObjectInputStream inputStream = null;
        private ObjectOutputStream outputStream = null;

        public Connect(Socket clientSocket) {
            this.client = clientSocket;
            try {
                this.inputStream = new ObjectInputStream(this.client.getInputStream());
                this.outputStream = new ObjectOutputStream(this.client.getOutputStream());
            } catch (Exception e1) {
                try {
                    this.client.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void run() {
            try {
                String ip = (String) inputStream.readObject();
                NuggetServerInfo info = NuggetServerInfoLog.getInstance().getReplicationServer(ip);
                this.outputStream.writeObject(info);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (this.client != null) {
                    try {
                        this.client.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }
}
